#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <err.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/msepoll.h>
#include <libmslog/mslog.h>
#include <libmsprotocol/msprotocol.h>

#include <srt/srt.h>

#define FLAG "samlpe_srtserver"
static char * pinurl=ms_null;
static char * pouturl=ms_null;
void* srtserver_send(void* args)
{
	URLVal urlval_out;
	memset(&urlval_out,0,sizeof(URLVal));
	ms_memcpy(&urlval_out, args, sizeof(URLVal));
	

	URLVal urlval_in;
	memset(&urlval_in,0,sizeof(URLVal));
	urlval_in.purl_ptl=msprotocol_api_match(PTLNAME_UDP);
	ms_strcpy(urlval_in.url_ctt.url, pinurl);
	urlval_in.url_ctt.urlctt_opt.udp_opt.interfacein="p2p1";
	urlval_in.url_ctt.urlctt_opt.udp_opt.localhostipin="192.168.200.244";
	if(urlval_in.purl_ptl->url_open(&urlval_in.url_ctt)<0){
		ms_errexit(-1, "Open in url failed");
	}
	
	char data[1316]={0};
	while (1){
		int recvlen=urlval_in.purl_ptl->url_read(&urlval_in.url_ctt,data,sizeof(data));
		if(recvlen>0){
			if (urlval_out.purl_ptl->url_write(&urlval_out.url_ctt, data , recvlen)<0){
				printf("srt_recv: %s\r\n", srt_getlasterror_str());
				break;
			}
		}
	}
	urlval_in.purl_ptl->url_close(&urlval_in.url_ctt);
	urlval_out.purl_ptl->url_close(&urlval_out.url_ctt);
	return NULL;
}
int main(int argc, char **argv)
{
	mslog_api_setopt(54,ms_null,0);
	if(3!=argc){
		ms_error("usage:%s   inurl   outurl",argv[0]);
		mslog_api_unsetopt();
		return -1;
	}
	pinurl=argv[1];
	pouturl=argv[2];
	msprotocol_api_init();
	register_protocol();
	srt_setloglevel(4);
	
	URLVal urlval_out;
	memset(&urlval_out,0,sizeof(URLVal));
	urlval_out.purl_ptl=msprotocol_api_match(PTLNAME_SRT);
	ms_memset(&urlval_out.url_ctt,0,sizeof(URLContext));

	ms_strcpy(urlval_out.url_ctt.url, pouturl);
	urlval_out.url_ctt.flags|=FLAG_WRITE;

	
	urlval_out.url_ctt.urlctt_opt.srt_opt.listen=1;
	if(urlval_out.purl_ptl->url_open(&urlval_out.url_ctt)<0){
		ms_errexit(-1, "Open out url failed");
	}
	char buf[2048]={0};
	int len=0;
	int recver=0;

	while(1){
		recver=urlval_out.purl_ptl->priv_func.srt.accept(&urlval_out.url_ctt);
		if(recver<0){
			ms_errret(-1, "url_accept error");
		}

		pthread_t rcvthread;
		pthread_create(&rcvthread, NULL, srtserver_send, &urlval_out);
		ms_sleep(1);
	}	
	urlval_out.purl_ptl->url_close(&urlval_out.url_ctt);
	msprotocol_api_deinit();
	mslog_api_unsetopt();
}
#undef MAIN_C

